package com.zhkj.txg.module.cart.ui

import android.util.Log
import android.view.View
import android.widget.CheckBox
import android.widget.ImageView
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.scale
import androidx.lifecycle.Observer
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.Gson
import com.mcxtzhang.swipemenulib.SwipeMenuLayout
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.SPUtil
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.cart.adapter.OnCartItemSelectedListener
import com.zhkj.txg.module.cart.entity.CartProductEntity
import com.zhkj.txg.module.cart.vm.CartViewModel
import com.zhkj.txg.module.home.entity.ShopInfo
import com.zhkj.txg.module.order.ui.OrderSubmitActivity
import com.zhkj.txg.module.product.ui.ProductDetailActivity
import com.zhkj.txg.utils.ImageUtils
import kotlinx.android.synthetic.main.fragment_cart_new.*
import java.lang.Exception

class CartFragmentNew : ViewModelFragment<CartViewModel>() {

    private var mAdapter: BaseQuickAdapter<CartProductEntity, BaseViewHolder>? = null
    private var mutableList = mutableListOf<CartProductEntity>()

    override fun setViewModel(): CartViewModel = createViewModel(false)
    override val layoutResId: Int = R.layout.fragment_cart_new

    private val listener = object : OnCartItemSelectedListener {
        // 选中状态发生变化
        override fun changed() {
            refreshStatusAndPrice()
        }

        // 数量变化
        override fun numberChange(uiPosition: Int, type: Int, originNumber: Int, maxCount: Int) {
            setCartNumber(uiPosition, type, originNumber, maxCount)
            refreshStatusAndPrice()
        }

        // 删除购物车item
        override fun itemDelete(uiPosition: Int) {
            showConfirmPopupWindow(uiPosition)
        }

        override fun itemClick(uiPosition: Int, product: CartProductEntity) {
            if (mode == 0) {
                if (product.isGoodsOnSale()) ProductDetailActivity.normalProduct(
                    requireContext(),
                    product.goodsId,
                    true
                )
            } else {
//                (cartAdapter.data[uiPosition] as? CartProductEntity)?.selected =
//                    (cartAdapter.data[uiPosition] as? CartProductEntity)?.selected?.not() ?: false
//                refreshStatusAndPrice(true)
            }
        }
    }

    /**
     * 0 - 结算模式,1 - 编辑模式
     */
    private var mode = 0

    private var refresh = false
    private var refreshAll = false

    override fun initUI() {
        // 设置状态栏高度、编辑按钮点击事件
        titleCart.setFragmentStatusBar()
        titleCart.setRightClickListener(View.OnClickListener {
            mode = if (mode == 0) 1 else 0
            refreshModeStatus()
        })

        mAdapter = object : BaseQuickAdapter<CartProductEntity, BaseViewHolder>(R.layout.item_cart_product_new) {
            override fun convert(helper: BaseViewHolder, item: CartProductEntity) {
                helper.setText(R.id.tvCartProductName, item.goodsName)
                    .setText(R.id.tvCartProductPrice, SpanUtil.setMoneySymbol(item.goodsPrice, false))
                    .setText(R.id.etNum, item.goodsNumber.toString())
                helper.getView<CheckBox>(R.id.cbCartCheck).isChecked = item.selected
                val imageView = helper.getView<ImageView>(R.id.ivCartShopProduct)
                ImageUtils.loadRoundCornerImage(context, imageView, item.image)
            }
        }
        mAdapter?.let {
            it.addChildClickViewIds(R.id.cbCartCheck, R.id.viewProduct, R.id.tvDelete, R.id.tvMinus, R.id.tvPlus)
            it.setOnItemChildClickListener { adapter, view, position ->
                (adapter.data[position] as? CartProductEntity)?.let {
                    when (view.id) {
                        // 选中购物车商品
                        R.id.cbCartCheck -> {
                            it.selected = !it.selected
                            listener.changed()
                        }
                        R.id.tvMinus -> {// 减号按钮监听
                            listener.numberChange(position, 0, it.goodsNumber, it.storeCount ?: 9999)
                        }
                        R.id.tvPlus -> {// 加号按钮监听
                            listener.numberChange(position, 1, it.goodsNumber, it.storeCount ?: 9999)
                        }
//                    // 点击商品
//                    R.id.viewProduct -> {
//                        listener?.itemClick(position, it)
////                    ProductDetailActivity.normalProduct(context, it.goodsId, true)
//                    }
                        // 删除按钮
                        R.id.tvDelete -> {
//                        helper.getView<SwipeMenuLayout>(R.id.viewSwipe).quickClose()
                            viewModel.deleteCart(AccountManager.getToken(), it.cartId.toString())
                        }
                        else -> Unit
                    }
                }
            }
        }
        // 设置热卖商品Adapter
        with(rvCartProduct) {
            adapter = mAdapter
        }
//        with(productAdapter) {
//            setEmptyView(R.layout.layout_empty_data)
//            setHeaderView(createHeaderView())
//        }
        // 全选按钮点击监听
        cbCartAll.setOnCheckedChangeListener { buttonView, isChecked ->
            if (buttonView.isPressed) {
                for (item in mAdapter?.data!!) {
                    item.selected = isChecked
                }
                mAdapter?.notifyDataSetChanged()
            }
            refreshStatusAndPrice()
        }
        // 结算按钮点击监听
        tvCartBuy.setOnClickListener {
            val builder = StringBuilder()
            mAdapter?.data?.let { it2 ->
                for (item in it2) {
                    if (item.selected) {
                        builder.append(item.cartId).append(",")
                    }
                }
            }
            if (builder.isNotEmpty()) builder.deleteCharAt(builder.lastIndex)
            OrderSubmitActivity.cartBuy(requireContext(), builder.toString())
        }
        // 删除按钮点击监听
        tvCartDelete.setOnClickListener {
            val cartIds = mutableListOf<String>()
            mAdapter?.data?.let { it2 ->
                for (item in it2) {
                    if (item.selected) {
                        cartIds.add(item.cartId.toString())
                    }
                }
            }
            viewModel.deleteCart(AccountManager.getToken(), cartIds)
        }
        // 滚动到顶部
        ivCartTop.setOnClickListener {
            rvCartProduct.scrollToPosition(0)
        }
        refreshCart.setOnRefreshListener {
            mode = 0
            refreshModeStatus()
            initData()
        }
    }

    @Suppress("UNCHECKED_CAST")
    override fun initViewModel() {
        // 购物车商品观察者
        viewModel.cartLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                response.response?.data?.let {
                    mutableList.clear()
                    if (it.cartList.isNullOrEmpty()) {
                        mAdapter?.notifyDataSetChanged()
                        refreshCart.finishRefresh()
                        refreshStatusAndPrice()
                        cbCartAll.isChecked = false
                        return@let
                    }
                    // 数据填充
                    it.cartList.get(0).goodsList.let {
                        mutableList.addAll(it)
                    }
                    mAdapter?.setNewData(mutableList)
                    mAdapter?.notifyDataSetChanged()
                    refreshStatusAndPrice()
                    refreshCart.finishRefresh()
                }
            } else if (response.status == HttpResponseStatus.Status.FAILURE) refreshCart.finishRefresh(false)
        })
        // 购物车商品数量改变观察者
        viewModel.changeNumberLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                mAdapter?.data?.let { it2 ->
                    for (item in it2) {
                        if (item.cartId == it.cartId) {
                            item.goodsNumber = it.currentNumber
                        }
                    }
                }
                refreshStatusAndPrice()
            } else if (response.status == HttpResponseStatus.Status.FAILURE) mAdapter?.notifyDataSetChanged()
        })
        // 购物车商品删除观察者
        viewModel.deleteCartLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                mode = 0
                refreshModeStatus()
                getCart()
            }
        })
        // 购物车商品刷新观察者
        viewModel.cartChangeSubscribe().observe(viewLifecycleOwner, Observer { refresh = true })
        // 切换账户观察者
        viewModel.accountChangeSubscribe().observe(viewLifecycleOwner, Observer { refreshAll = true })
        // 会员状态观察者
        viewModel.memberStatusChangeSubscribe().observe(viewLifecycleOwner, Observer { refreshAll = true })
    }

    override fun initData() {
        getCart()
    }

    private fun getCart() {
        // 获取购物车参数
        val shopInfo1 = SPUtil.getInstance().getString(AccountManager.SHOP_INFO)
        val shopInfo2 = try {
            val gson = Gson()
            gson.fromJson<ShopInfo>(shopInfo1, ShopInfo::class.java)
        } catch (e: Exception) {
            null
        }
        viewModel.getCartNew(hashMapOf("shop_id" to shopInfo2?.id.toString()))
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            getCart()
        }
    }

    override fun onResume() {
        super.onResume()
        if (refreshAll) {
            rvCartProduct.scrollToPosition(0)
            getCart()
            refreshAll = false
            refresh = false
        }
        if (refresh) {
            rvCartProduct.scrollToPosition(0)
            refresh = false
            getCart()
        }
    }

    private fun refreshModeStatus() {
        titleCart.setRightTextContent(getString(if (mode == 0) R.string.edit else R.string.done))
        tvCartTotal.visibility = if (mode == 0) View.VISIBLE else View.INVISIBLE
        tvCartDelete.visibility = if (mode == 0) View.GONE else View.VISIBLE
        tvCartBuy.visibility = if (mode == 0) View.VISIBLE else View.GONE
    }

    /**
     * 刷新选中状态以及总价
     */
    private fun refreshStatusAndPrice(refresh: Boolean = false) {
        mAdapter?.notifyDataSetChanged()
//        mAdapter.refreshStatusEntity(ignoreOnSale = mode == 1)
//        tvCartTotal.text = SpanUtil.setPrefixMoneyStr("合计:", cartAdapter.checkStatusEntity.totalPrice)
        var totalPrice = 0f
        tvCartTotal.text = ""
        mAdapter?.data?.let {
            for (item in it) {
                if (item.selected) {
                    totalPrice += (item.goodsPrice.toFloat() * item.goodsNumber)
                } else {
                    cbCartAll.isChecked = false
                }
            }
        }

        tvCartTotal.text = buildSpannedString {
            append("合计:￥").bold { scale(1.2F) { append(String.format("%.2f", totalPrice)) } }
        }
        tvCartBuy.isEnabled = totalPrice > 0
        tvCartDelete.isEnabled = totalPrice > 0
    }

    /**
     * 设置商品数量,并刷新价格
     */
    private fun setCartNumber(uiPosition: Int, type: Int, originNumber: Int, maxStock: Int) {
        mAdapter?.data?.get(uiPosition)?.let {
            if (originNumber > maxStock) {
                toast(getString(R.string.more_than_stock))
                return
            }
            if (originNumber <= 0) {
                toast(getString(R.string.product_number_change))
                return
            }
            when (type) {
                0 -> viewModel.changeCartNumber(it.cartId, originNumber - 1)
                1 -> viewModel.changeCartNumber(it.cartId, originNumber + 1)
                else -> viewModel.changeCartNumber(it.cartId, originNumber)
            }
        }
    }

//    private fun createHeaderView(): View {
//        return layoutInflater.inflate(R.layout.item_cart_top, null).apply {
//            // 设置购物车商品Adapter
//            with(findViewById<RecyclerView>(R.id.rvCart)) {
//                layoutManager = LinearLayoutManager(activity)
//                adapter = cartAdapter
//                (itemAnimator as? DefaultItemAnimator)?.supportsChangeAnimations = false
//            }
//            cartAdapter.setEmptyView(R.layout.layout_empty_data)
//        }
//    }

    private fun showConfirmPopupWindow(uiPosition: Int) {
//        (cartAdapter.data[uiPosition] as? CartProductEntity)?.let {
//            viewModel.deleteCart(AccountManager.getToken(), it.cartId.toString())
//        }
    }
}